import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    // 购物相关路由
    {
      path: '/products',
      name: 'products',
      component: () => import('../views/ProductsView.vue'),
    },
    {
      path: '/products/:id',
      name: 'productDetail',
      component: () => import('../views/ProductDetailView.vue'),
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('../views/CartView.vue'),
    },
    {
      path: '/checkout',
      name: 'checkout',
      component: () => import('../views/CheckoutView.vue'),
      meta: {
        requiresAuth: true
      }
    },
    // 用户认证路由
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: {
        requiresAuth: false,
        layout: 'auth'
      }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: {
        requiresAuth: false,
        layout: 'auth'
      }
    },
    // 用户中心路由
    {
      path: '/user',
      name: 'userCenter',
      component: () => import('../views/UserCenter.vue'),
      meta: {
        requiresAuth: true
      },
      children: [
        {
          path: 'profile',
          name: 'userProfile',
          component: () => import('../views/UserProfile.vue')
        },
        {
          path: 'orders',
          name: 'userOrders',
          component: () => import('../views/UserOrders.vue')
        },
        {
          path: 'addresses',
          name: 'userAddresses',
          component: () => import('../views/UserAddresses.vue')
        },
        {
          path: 'membership',
          name: 'userMembership',
          component: () => import('../views/UserMembership.vue')
        }
      ]
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 从本地存储加载用户状态
  userStore.loadFromLocalStorage()
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    // 未登录，重定向到登录页面
    next({ name: 'login', query: { redirect: to.fullPath } })
  } else if (to.meta.requiresAuth === false && userStore.isLoggedIn) {
    // 已登录但访问认证页面，重定向到个人中心
    next({ name: 'userProfile' })
  } else {
    next()
  }
})

export default router
